import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);


const routers = [{
    path: '/login',
    name: 'login',
    component: () => import('@/pages/login/index'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/',
    meta: {
      title: '首页'
    },
    redirect: {
      name: 'index'
    },
    component: () => import('@/pages/index'),
    children: [{
        path: '/',
        name: 'index',
        component:  () => import('@/pages/one'),
        meta: {
          title: 'index'
        }
      },
      {
        path: '/one',
        name: 'one',
        component: () => import('@/pages/Page1'),
        meta: {
          title: 'one'
        }
      },
      {
        path: '/two',
        name: 'two',
        component: () => import('@/pages/Page2'),
        meta: {
          title: 'two'
        }
      },
    ]
  },
  {
    path: '*',
    redirect: {
      name: '/'
    }
  }
];

const router = new Router({
  base: 'login',
  routes: routers
})

router.beforeEach((to, from, next) => {
  let user = sessionStorage.getItem('user');
  console.log('user: ', user);
  if (to.meta.title) {
    document.title = to.meta.title
  }
  if (!user) {
    if (to.path === '/login') {
      next()
    } else {
      // next()
      next({
        path: '/login'
      })
    }
  } else {
    if (to.path === '/login') {
      next({
        path: '/'
      })
    } else {
      next()
    }
  }
})

export default router